package service

import (
	"context"
	"errors"
	"github.com/gogf/gf/v2/frame/g"
	v1 "go-websocket/api/im/v1"
	"go-websocket/utility"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type vendorService struct {}

var Vendor = new(vendorService)


func (s *vendorService) GetMemberPhotos (req *v1.GetMemberPhotosReq) (results []map[string]interface{}, err error) {

	//mongo
	conn := utility.MgConn("default")
	chatMemberColl := conn.GetColl("txzh_chat_member")
	cursor, err := chatMemberColl.Find(context.TODO(), bson.M{"list_id": req.ListId, "userid": bson.M{"$ne": 1}}, options.Find().SetLimit(10).SetProjection(bson.M{"user_id": 1}))

	if err != nil {
		return nil, err
	}

	for cursor != nil && cursor.Next(context.TODO()) {
		// 创建一个映射来存储单个文档的数据
		var result map[string]interface{}
		err = cursor.Decode(&result)
		if err != nil {
			return nil, err
		}
		results = append(results, result)
	}
	// 遍历切片，记录需要删除的索引
	indexesToDelete := []int{}
	for k, v := range results {
		userIdTmp, ok := v["user_id"].(int32)
		if ok {
			userId := int(userIdTmp)
			userInfo, err := User.GetUserInfo(userId)


			if err != nil {
				g.Log().Error(context.TODO(), err)
				return nil, err
			} else {
				if userInfo.face == "" {
					//TODO 删除k键元素
					//添加需要删除的索引
					indexesToDelete = append(indexesToDelete, k)
				} else {
					v["photo"] = userInfo.face
				}

			}
		} else {
			g.Log().Error(context.TODO(), "GetMemberPhotos-用户ID断言失败")
			return nil, errors.New("系统错误")

		}

	}

	// 删除需要删除的元素
	for _, index := range indexesToDelete {
		// 利用切片技巧删除元素
		results = append(results[:index], results[index+1:]...)
	}



	return results, nil
}